//
//  PopWebViewController.m
//  KidReading
//
//  Created by linziyuan on 16/5/6.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "PopWebViewController.h"
#import "ConstDefine.h"

@implementation UIViewController (JSExtend)

ASSOCIATED(closeType, setCloseType, NSString*, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
ASSOCIATED(defineInfo, setDefineInfo, id, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
@end

@interface PopWebViewController ()<UIWebViewDelegate,UIViewControllerTransitioningDelegate,VCTransitionsDelegate>

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic, strong) UIActivityIndicatorView *indicator;

@property(nonatomic,strong)void(^disMiss)(void);

@end

@implementation PopWebViewController
{
    BOOL _isPhone;
    BaseAnimation* _animation;
    UIWindow* window;
}

static PopWebViewController * singlePopViewController = nil;

+ (instancetype)shareLastInstance
{
    return singlePopViewController;
}

- (instancetype)init {
    if (self = [super init]) {
        singlePopViewController = self;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        _isPhone = YES;
    }else {
        _isPhone = NO;
    }
    _animation = [[ModalAnimation alloc] init];
    _animation.delegate = self;
    self.view.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.25];
    self.contentView.backgroundColor = [UIColor clearColor];
    [self setUpUI];
}

- (void)setUpUI {
    
    self.contentView.backgroundColor = [UIColor clearColor];
    //
    
    [self.view addSubview:self.webView];
    self.webView.delegate = self;
    self.webView.paginationMode = UIWebPaginationModeUnpaginated;
    [self.webView setOpaque:NO];
    CGFloat topY = 0;
    CGFloat btnWidth = 40.0;
    CGFloat rightX = 15;
    if (_isPhone) {
        topY = 20.0;
        btnWidth = 25.0;
        rightX = 10.0;
    }
    [self.webView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.view).offset(topY);
    }];
    self.webView.backgroundColor = [UIColor clearColor];
    //
    self.indicator = [[UIActivityIndicatorView alloc] init];
    self.indicator.translatesAutoresizingMaskIntoConstraints = NO;
    [self.contentView addSubview:self.indicator];
    self.indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [self.indicator lyt_setSize:CGSizeMake(30, 30)];
    [self.indicator lyt_centerXInParentWithOffset:0];
    if ([DataProcessing shareSingle].deviceType == DevicesTypes_iPhone) {
        [self.indicator lyt_centerYInParentWithOffset:-10];
    }else {
        [self.indicator lyt_centerYInParentWithOffset:-70];
    }
    
    //
    
    self.closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.closeBtn setBackgroundImage:[UIImage imageNamed:@"page_btn_cloes_normal.png"] forState:UIControlStateNormal];
    self.closeBtn.alpha = 0.5;
    [self.view addSubview:self.closeBtn];
    [self.closeBtn JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.size.JRMAS_equalTo(CGSizeMake(btnWidth, btnWidth));
        make.right.equalTo(self.view).offset(-rightX);
        make.top.equalTo(self.view).offset(topY);
    }];
    [self.closeBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    //self.closeBtn.hidden = YES;
    
    if (self.url.length > 0) {
        //[self loadRequestWithUrl:self.url];
    }
}

- (void)dealloc
{
    
}

- (void)clickBack {
    [self.webView stopLoading];
    if (_disMiss) {
        self.disMiss();
    }else{
        [self willMoveToParentViewController:nil];
        [self.view removeFromSuperview];
    }
    self.isShowing = NO;
    //[self removeFromParentViewController];
    //objc_setAssociatedObject(self, "popWebVC", nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)loadRequestWithUrl:(NSString *)url {
    self.webView = [[UIWebView alloc] init];
    self.webView.mediaPlaybackRequiresUserAction = NO;
    self.webView.allowsInlineMediaPlayback = YES;
    NSDictionary* baseInfo = [[NetRequestWithCache_JR shareSingle] netRequestAddBaseInfo:@{}];
    url = [NetRequest netFullUrl_Get:url fromDict:baseInfo];
#ifdef __Debug_JSLog
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
#else
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
#endif
    [self.webView loadRequest:request];
    
}

+ (void)popWebVCWithCurrentVC:(UIViewController *)currentVC url:(NSString *)url {
    if (!currentVC || url.length<=0) {
        return;
    }
    if ([PopWebViewController shareLastInstance].isShowing) {
        return;
    }
    //currentVC.view.backgroundColor = [UIColor clearColor];
    PopWebViewController *popWebVC = [[PopWebViewController alloc] init];
    //popWebVC.url = url;
    popWebVC.url = url;
    [popWebVC loadRequestWithUrl:url];
    popWebVC.isShowing = YES;
    
    popWebVC.title = [NSString stringWithFormat:@"WebView_%@", url];
    
    //popWebVC.modalPresentationStyle = UIModalPresentationCustom;
    
    objc_setAssociatedObject(popWebVC, "popWebVC", popWebVC, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [currentVC addChildViewController:popWebVC];
    [currentVC.view addSubview:popWebVC.view];
    [popWebVC didMoveToParentViewController:currentVC];
}


+ (void)closePop
{
    [[PopWebViewController shareLastInstance] clickBack];
}
+ (instancetype)popWindowUrl:(NSString *)url
{
    if ([PopWebViewController shareLastInstance].isShowing) {
        return nil;
    }
    //currentVC.view.backgroundColor = [UIColor clearColor];
    PopWebViewController *popWebVC = [[PopWebViewController alloc] init];
    //popWebVC.url = url;
    popWebVC.url = url;
    [popWebVC loadRequestWithUrl:url];
    popWebVC.isShowing = YES;
    
    popWebVC.title = [NSString stringWithFormat:@"WebView_%@", url];
    
    //popWebVC.modalPresentationStyle = UIModalPresentationCustom;
    
    objc_setAssociatedObject(popWebVC, "popWebVC", popWebVC, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [popWebVC showWindowUrl:url];
    return popWebVC;
}

- (void)dismissWindw:(CGRect)frame
{
    [UIView animateWithDuration:0.3 animations:^{
        window.frame = frame;
    } completion:^(BOOL finished) {
        window = nil;
    }];
}
- (void)showWindowUrl:(NSString*)url
{
    CGRect frame = [[UIScreen mainScreen] bounds];
    frame.origin.y += frame.size.height;
    window = [[UIWindow alloc] initWithFrame: frame];
    window.windowLevel = UIWindowLevelStatusBar-3;
    window.rootViewController = self;
    //
    [window makeKeyAndVisible];
    frame.origin.y -= frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        window.frame = frame;
    } completion:^(BOOL finished) {
    }];
    //
    frame.origin.y += frame.size.height;
    __weak PopWebViewController* _self = self;
    self.disMiss = ^{
        [_self dismissWindw:frame];
    };
}

#pragma mark WebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //self.closeBtn.hidden = NO;
    [self.indicator stopAnimating];
    [JSDataProcessing reg_poptool_js:self.webView];
    [JSDataProcessing js_poptool_clean_device_width:self.webView];
    [JSDataProcessing setUinfoCallback:webView];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {

    [self.indicator stopAnimating];
     if (error.code != 101 && error.code != (-999)) {
        [self clickBack];
        [[NetCacheData shareSingle] cleanNetCacheDataWithPort:self.url baseUrl:nil keyID:nil completed:nil];
    }
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    [self.indicator startAnimating];
    self.closeType = CLOSECHILD;
    [JSDataProcessing startURL:request.URL.absoluteString webView:self.webView currentVC:self];
    if ([request.URL.absoluteString hasPrefix:@"localcall::"]) {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
